package devices

import (
	"context"

	"gitee.com/zhuhuan12/go-modbus"
	"github.com/gogf/gf/v2/frame/g"
)

// 灯光 的控制
type FengSu struct {
	Product    string // 产品Key
	ModbusAddr int8   // modbus地址
	Speed      int    // 风速
}

func (l *FengSu) NewDevice(modbusValue int8) Device {
	return &FengSu{
		ModbusAddr: modbusValue,
		Product:    "fengsu",
		Speed:      100,
	}
}

func (l *FengSu) GetProductKey() string {
	return l.Product
}

func (l *FengSu) GetModbusAddr() int8 {
	return l.ModbusAddr
}

func (p *FengSu) HandleData(data []byte) (out []byte, err error) {
	out = []byte{}
	if data[1] == 0x03 { // 读取
		beginAddr := int(data[2])<<8 | int(data[3]) // 起始地址
		readLen := int(data[4])<<8 | int(data[5])   // 读取长度
		out = []byte{byte(p.ModbusAddr), 0x03, byte(readLen * 2)}
		for i := 0; i < readLen; i++ {
			addr := beginAddr + i // 对应的地址
			switch addr {
			case 0:
				out = append(out, byte(p.Speed>>8), byte(p.Speed)) // 压力
			}
		}
		g.Log().Debug(context.Background(), "读取风速", p.Speed)
		p.Speed++
	}
	intValue := modbus.CRC16(out)
	out = append(out, byte(intValue), byte(intValue>>8))
	return
}
